import { defineStore } from 'pinia'
import { ref } from 'vue'
import Color from 'color'

export const useThemeStore = defineStore('theme', () => {
  // 是否暗黑模式
  const isDark = ref(false)
  
  // 主题色
  const primaryColor = ref('#409eff')
  
  // 切换暗黑模式
  const toggleDark = () => {
    isDark.value = !isDark.value
    if (isDark.value) {
      document.body.classList.add('dark')
      document.documentElement.classList.add('dark')
    } else {
      document.body.classList.remove('dark')
      document.documentElement.classList.remove('dark')
    }
    // 保存到本地
    localStorage.setItem('theme-dark', String(isDark.value))
  }
  
  // 生成主题色的不同深浅
  const generateThemeColors = (color: string) => {
    try {
      const colorInstance = Color(color)
      for (let i = 1; i <= 9; i++) {
        document.documentElement.style.setProperty(
          `--el-color-primary-light-${i}`,
          colorInstance.lighten(i / 10).hex()
        )
        if (i <= 2) {
          document.documentElement.style.setProperty(
            `--el-color-primary-dark-${i}`,
            colorInstance.darken(i / 10).hex()
          )
        }
      }
    } catch (error) {
      console.error('生成主题色失败:', error)
    }
  }
  
  // 设置主题色
  const setPrimaryColor = (color: string) => {
    primaryColor.value = color
    // 设置 CSS 变量
    document.documentElement.style.setProperty('--el-color-primary', color)
    // 生成主题色
    generateThemeColors(color)
    // 保存到本地
    localStorage.setItem('theme-primary', color)
  }
  
  // 初始化主题
  const initTheme = () => {
    // 初始化暗黑模式
    const dark = localStorage.getItem('theme-dark')
    if (dark === 'true') {
      isDark.value = true
      document.body.classList.add('dark')
      document.documentElement.classList.add('dark')
    }
    
    // 初始化主题色
    const primary = localStorage.getItem('theme-primary')
    if (primary) {
      primaryColor.value = primary
      document.documentElement.style.setProperty('--el-color-primary', primary)
      // 生成主题色
      generateThemeColors(primary)
    }
  }
  
  return {
    isDark,
    primaryColor,
    toggleDark,
    setPrimaryColor,
    initTheme
  }
}) 